package com.wva.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.wva.common.constant.AuthenticationConst;
import com.wva.common.context.UserContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 获取登录用户id放到上下文中
 */
@Slf4j
public class AuthContextInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader(AuthenticationConst.LOGIN_USER_IN_HEADER);
        if (!StrUtil.isEmpty(userId)) {
            UserContext.setUserId(Long.parseLong(userId));
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        UserContext.clear();
    }
}
